package com.example.security;

import java.io.IOException;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.web.authentication.WebAuthenticationDetailsSource;
import org.springframework.stereotype.Component;
import org.springframework.web.filter.OncePerRequestFilter;

import com.example.redis.service.RedisLoginService;

import lombok.extern.slf4j.Slf4j;

@Slf4j
@Component
public class JwtAuthenticationTokenFilter extends OncePerRequestFilter {

	@Autowired
	private UserDetailsService userDetailsService;

	@Autowired
	private RedisLoginService redisLoginService;

	@Autowired
	private JwtTokenUtil jwtTokenUtil;

	@Value("${security.jwt.header}")
	private String tokenHeader;

	@Value("${security.jwt.tokenHead}")
	private String tokenHead;

	@Value("${security.single_login}")
	private Boolean isSingleLogin;

	@Override
	protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain chain)
			throws ServletException, IOException {
		String authHeader = request.getHeader(this.tokenHeader);
		if (authHeader != null && authHeader.startsWith(tokenHead)) {
			String authToken = authHeader.substring(tokenHead.length());
			String username = jwtTokenUtil.getUsernameFromToken(authToken);
			log.debug("checking authentication " + username);
			boolean flag = false;
			if (null != authToken && null != username) {
				if (isSingleLogin) {
					if (redisLoginService.validate(username, authToken)) {
						redisLoginService.login(username, authToken);
						flag = true;
					} else {
						flag = false;
					}
				} else {
					flag = true;
				}
				if (flag && null == SecurityContextHolder.getContext().getAuthentication()) {
					UserDetails userDetails = this.userDetailsService.loadUserByUsername(username);
					if (jwtTokenUtil.validateToken(authToken, userDetails)) {
						UsernamePasswordAuthenticationToken authentication = new UsernamePasswordAuthenticationToken(
								userDetails, null, userDetails.getAuthorities());
						authentication.setDetails(new WebAuthenticationDetailsSource().buildDetails(request));
						log.debug("authenticated user " + username + ", setting security context");
						SecurityContextHolder.getContext().setAuthentication(authentication);
					}
				}
			}
		}
		chain.doFilter(request, response);
	}

}
